package org.example.controller;

import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.mapper.JobMapper;
import org.example.pojo.*;
import org.example.service.*;
import org.example.utils.JobAnalyzer;
import org.example.service.*;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
public class JobController {

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private JobService jobService;
    @Autowired
    private CompanyService companyService;

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private CompanymessageService companymessageService;

    @Autowired
    private PersonalmessageService personalmessageService;
    JobAnalyzer analyzer = new JobAnalyzer();

    //获取所有工作信息
    @PostMapping("/job/getJobList")
    public Result<List<Job>> getAllJobs() {
        List<Job> jobs = jobMapper.selectAllJobs();
        return Result.success(jobs);
    }

    //搜索工作信息
    @PostMapping("/job/getJobBys")
    public Result<PageBean<Job>> searchJob(Integer jobId, String jobTitle, String location, Integer pageNum, Integer pageSize, String city, String industry) {
        //1.创建一个PageBean对象
        PageBean<Job> pb = new PageBean<>();

        //2.开启分页插件功能
        PageHelper.startPage(pageNum, pageSize);

        List<Job> jobs = new ArrayList<>();

        if(industry == null){
            jobs = jobMapper.searchJob(jobId, jobTitle, location, null, null, null);
        }

        //将数据转为Page类型
        else if(!industry.equals("")){
            //1.参数校验
            if(industry.equals("3k以下")){
                industry = "1-3k";
            }else if(industry.equals("20k以上")){
                industry = "20-50k";
            }

            Pattern pattern = Pattern.compile("\\d+");
            Matcher matcher = pattern.matcher(industry);

            List<String> numbers = new ArrayList<>(); // 创建一个ArrayList来存储数字

            while (matcher.find()) {
                numbers.add(matcher.group()); // 将匹配到的每个数字添加到列表中
            }

            if((location == null && !city.equals("")) || (location == "" && !city.equals(""))){
                location = city;
            }

            Integer minsalary = Integer.parseInt(numbers.get(0)) * 12;
            Integer maxsalary = Integer.parseInt(numbers.get(1)) * 12;
            jobs = jobMapper.searchJob(jobId, jobTitle, location, industry, minsalary, maxsalary);
        }else{
            jobs = jobMapper.searchJob(jobId, jobTitle, location, null, null, null);
        }


        Page<Job> page = (Page<Job>) jobs;

        //把数据填充到PageBean对象中
        pb.setTotal(page.getTotal());
        pb.setItem(page.getResult());
        return Result.success(pb);
    }

    //分页获取职位信息
    //文章列表
    @PostMapping("/job/page")
    public Result<PageBean<Job>> list(Integer pageNum, Integer pageSize){
        PageBean<Job> pb = jobService.list(pageNum, pageSize);
        return Result.success(pb);
    }

    //根据id获取职位信息
    @PostMapping("/job/jobDetails")
    public Result<JobDto> getJobById(Integer jobId){
        JobDto jobDto = jobService.getJobById(jobId);
        return Result.success(jobDto);
    }

    //用户进行简历投递
    @PostMapping("/job/postJob")
    public Result<String> postJob(Integer userId, Integer jobId, Integer companyId){
        //根据用户id得到简历id
        Integer resumeId = resumeService.getResumeIdByUserId(userId);
        //查看是否存在信息
        Personalmessage pp = personalmessageService.selectByUserIdAndJobIdAndCompanyId(userId, jobId, companyId, resumeId);
        if(pp == null){
            //将投递信息插入到用户个人消息表中
            personalmessageService.insertPersonalMessage(userId, companyId, jobId, resumeId);
            //将投递信息插入到公司消息表中
            companymessageService.insertCompanyMessage(companyId, jobId, userId, resumeId);
        }else{
            //更新消息表
            personalmessageService.updatePostIdMessage(userId, companyId, jobId, resumeId);
        }
        return Result.success("投递成功");
    }

    //用户进行简历收藏
    @PostMapping("/job/favorJob")
    public Result<String> favorJob(Integer userId, Integer jobId, Integer companyId, Integer sss){
        //根据用户id得到简历id
        Integer resumeId = resumeService.getResumeIdByUserId(userId);
        //查看是否存在信息
        Personalmessage pp = personalmessageService.selectByUserIdAndJobIdAndCompanyId(userId, jobId, companyId, resumeId);
        if(sss == 1){
            if (pp == null) {
                //将收藏信息插入到用户个人消息表中
                personalmessageService.insertPersonalFavorMessage(userId, companyId, jobId, resumeId);
            }else{
                personalmessageService.updatePersonalFavorMessage(userId, companyId, jobId, resumeId);
            }
            return Result.success("收藏成功");
        }else{
            personalmessageService.updateFavorNullMessage(userId, companyId, jobId, resumeId);
            return Result.success("取消收藏");
        }
    }

    //查看用户对于岗位的投递状态
    @PostMapping("/job/checkPostJob")
    public Result<Personalmessage> checkPostJob(Integer userId, Integer jobId, Integer companyId){
        //查询用户对于该岗位的投递状态
        Personalmessage personalmessage = personalmessageService.selectStatus(userId, jobId, companyId);
        return Result.success(personalmessage);
    }

    //查看公司对于岗位的邀请状态
    @PostMapping("/job/checkCompanyInvite")
    public Result<Companymessage> checKCompanyInvite(Integer userId, Integer companyId, Integer postId){
        //查询用户对于该岗位的投递状态
        Companymessage companymessage = companymessageService.selectStatus(userId, postId, companyId);
        return Result.success(companymessage);
    }
    //逻辑删除职位信息
    @PostMapping("/job/deleteJob")
    public Result<String> deleteJob(Integer jobId, Integer status) {
        jobService.deleteJob(jobId, status);
        return Result.success("删除成功");
    }

    //获取公司发布的职位信息
    @PostMapping("/job/getCompanyJob")
    public Result<List<Job>> getCompanyJobList(Integer companyId){
        List<Job> jobs = jobService.getCompanyJobList(companyId);
        return Result.success(jobs);
    }

    //获取职位收到的简历信息
    @PostMapping("/job/getJobResumes")
    public Result<ResumeDto> getResumeList(Integer jobId, Integer companyId){
         List<Companymessage> companymessages = companymessageService.getResumeListByJobId(jobId, companyId);
         ResumeDto resumeDto = new ResumeDto();
         List<Resume> resumes = new ArrayList<>();
         List<Integer> approves = new ArrayList<>();
        for (Companymessage companymessage :companymessages) {
            Resume resume = resumeService.selectByUserId(companymessage.getUserId());
            resumes.add(resume);
            approves.add(companymessage.getApprove());
        }
        resumeDto.setResume(resumes);
        resumeDto.setApprove(approves);
        return Result.success(resumeDto);
    }
//    插入岗位信息
    @PostMapping("/job/insertJob")
    public Result<String> insertJob(String location,String hr,String tags,String name,String salary,Integer companyId,String description,String role,Integer experiment,String degree) throws NoApiKeyException, InputRequiredException, JsonProcessingException {
        Job job=new Job();
        job.setLocation(location);
        job.setHr(hr);
        job.setTags(tags);
        job.setName(name);
        job.setDescription(description);

        job.setSalary(salary);
        job.setDegree(degree);


        Company company=companyService.findCompanyById(companyId);
        String companyName=company.getName();
        job.setCompanyId(companyId);
        job.setCompanyName(companyName);
        String[] parts = salary.split("-"); // 使用"-"作为分隔符
        String firstPart = parts[0]; // 获取分割后数组的第一个元素
        Integer salaryYear=Integer.parseInt(firstPart)*12;
        String str_experiment="";
        switch (experiment) {
            case 0 -> {
                str_experiment="经验不限";
            }
            case 1 -> {
                str_experiment = "1-3年";
            }
            case 3 -> {
                str_experiment = "3-5年";
            }
            case 5 -> {
                str_experiment = "5-10年";
            }
            case 10 -> {
                str_experiment = "10年以上";
            }
        }
        job.setWorkYear(experiment);
        job.setSalaryYear(salaryYear);
        job.setExperience(str_experiment);
        String content=analyzer.callWithMessage(description);

        String regex = "(技术要求：)(.*?)(\\n|)$"
                + "|(工作领域：)(.*?)(\\n|)$"
                + "|(角色定位：)(.*?)(\\n|)$"
                + "|(工作经验：)(.*?)(\\n|)$";

        Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(content);
        String workRole = "无";
        String workField = "无";
        String workRequirements = "无";
        String workExperience = "无";

        while (matcher.find()) {
            if (matcher.group(1) != null) {
                workRequirements=matcher.group(2).trim();
                System.out.println("技术要求：" + matcher.group(2).trim());
            } else if (matcher.group(4) != null) {
                workField=matcher.group(5).trim();
                System.out.println("工作领域：" + matcher.group(5).trim());
            } else if (matcher.group(7) != null) {
                workRole=matcher.group(8).trim();
                System.out.println("角色定位：" + matcher.group(8).trim());
            } else if (matcher.group(10) != null) {
                workExperience=matcher.group(11).trim();
                System.out.println("工作经验：" + matcher.group(11).trim());
            }
        }
        job.setWorkRequirements(workRequirements);
        job.setWorkField(workField);
        job.setWorkRole(workRole);
        job.setWorkExperience(workExperience);
//        Pattern pattern = Pattern.compile("(?:技术要求：(.*?))?\\n?(工作领域：(.*?))?\\n?(角色定位：(.*?))?\\n?(工作经验：(.*?))(?=\\n|$)", Pattern.DOTALL);
//
//        Matcher matcher = pattern.matcher(content);
//        if (matcher.find()) {
//            String techRequirements = matcher.group(1) != null ? matcher.group(1) : "无";
//            String workField = matcher.group(2) != null ? matcher.group(2) : "无";
//            String rolePosition = matcher.group(3) != null ? matcher.group(3) : "无";
//            String experience = matcher.group(4) != null ? matcher.group(4) : "无";
//            job.setWorkRequirements(techRequirements);
//            job.setWorkField(workField);
//            job.setWorkRole(rolePosition);
//            job.setWorkExperience(experience);
//        } else {
//            System.out.println("没有匹配到任何信息。");
//        }
        jobService.insertJob(job);
        return Result.success("插入成功");
    }


    @GetMapping("/job/getCount")
    public Result<List<Integer>> getCompanyJobList(){
        List<Integer> counts = new ArrayList<>();
        Integer jobs = jobService.getCount(counts);
        Integer companies = companyService.getCount(counts);
        counts.add(jobs);
        counts.add(companies);
        return Result.success(counts);
    }

    @GetMapping("/job/getHotJobList")
    public Result<List<Job>> getHotJobList(){
        List<Job> jobs = jobService.getHotJobList();
        return Result.success(jobs);
    }

    //获取热门企业
    @PostMapping("/job/getTopJob")
    public Result<PageBean<Job>> getTopJob(Integer pageNum, Integer pageSize, String salary, String city) {
        //1.创建一个PageBean对象
        PageBean<Job> pb = new PageBean<>();

        //2.开启分页插件功能
        PageHelper.startPage(pageNum, pageSize);
        if(salary.equals("不限")){
            salary="";
        }
        if(city.equals("不限")){
            city="";
        }
        List<Job> jobs = new ArrayList<>();
        if(!salary.equals("")){
            Integer minSalary=Integer.parseInt(salary.split("-")[0]) * 12;
            Integer maxSalary=Integer.parseInt(salary.split("-")[1]) * 12;
            //将数据转为Page类型
            jobs =  companyService.getTopCompany(salary, city, minSalary, maxSalary);
        }else{
            jobs =  companyService.getTopCompany(salary, city, null, null);
        }
        Page<Job> page = (Page<Job>) jobs;

        //把数据填充到PageBean对象中
        pb.setTotal(page.getTotal());
        pb.setItem(page.getResult());
        return Result.success(pb);
    }

}
